const PermissionModel = require('../models/permissionModel');
const { getLogger } = require('../logger');
const { generateCacheKey, getCacheKeyPattern } = require('../cache/utils/cacheKeyGenerator');
const logger = getLogger('controllers.permissionController');
const { success, error, serverError, notFound, badRequest } = require('../utils/response');
const { logAudit } = require('../utils/auditLogger');
const { validateRequired, validateId } = require('../utils/validator');
const cacheService = require('../cache/cacheService');

// 获取权限列表
const getPermissions = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        // 构建过滤条件
        const filters = {};
        if (req.query.permission_name) filters.permission_name = req.query.permission_name;
        if (req.query.module_code) filters.module_code = req.query.module_code;
        if (req.query.permission_code) filters.permission_code = req.query.permission_code;
        if (req.query.status !== undefined) filters.status = req.query.status;

        if (req.query.permission_type !== undefined) filters.permission_type = req.query.permission_type;
        
        // 生成缓存键
        const cacheKey = generateCacheKey('permission', 'list', `${page}_${limit}_${JSON.stringify(filters)}`);
        
        // 尝试从缓存获取
        const cachedResult = await cacheService.get(cacheKey);
        if (cachedResult) {
            logger.debug('从缓存获取权限列表');
            await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'list', operation_desc: 'list' });
            return success(req, res, '获取权限列表成功', cachedResult);
        }

        const [permissions, total] = await Promise.all([
            PermissionModel.getAllPermissions(page, limit, filters),
            PermissionModel.getPermissionCount(filters)
        ]);
        
        const result = {
            data: permissions,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
        
        // 设置缓存
        await cacheService.set(cacheKey, result, 3600);
        
        await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'list', operation_desc: 'list' });
        return success(req, res, '获取权限列表成功', result);
    } catch (err) {
        logger.error('获取权限列表失败:', { error: err });
        return serverError(req, res, '获取权限列表失败');
    }
};

// 获取权限详情
const getPermission = async (req, res) => {
    try {
        const { id } = req.params;

        if (!validateId(id)) {
            return badRequest(req, res, '权限ID格式错误');
        }
        
        // 生成缓存键
        const cacheKey = generateCacheKey('permission', 'item', `permission_${id}`);
        
        // 尝试从缓存获取
        const cachedPermission = await cacheService.get(cacheKey);
        if (cachedPermission) {
            logger.debug('从缓存获取权限详情');
            await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'permission', target_entity_id: id });
            return success(req, res, '获取权限详情成功', cachedPermission);
        }

        const permission = await PermissionModel.getPermissionById(id);

        if (!permission) {
            return notFound(req, res, '权限不存在');
        }
        
        // 设置缓存
        await cacheService.set(cacheKey, permission, 3600);

        await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'permission', target_entity_id: id });
        return success(req, res, '获取权限详情成功', permission);
    } catch (err) {
        logger.error('获取权限详情失败:', { error: err });
        return serverError(req, res, '获取权限详情失败');
    }
};


// 获取用户ID获取权限码列表
const getUserPermissionCodes = async (req, res) => {
    try {
        const userId = req.user?.id || req.params.userId;

        if (!userId || !validateId(userId)) {
            return badRequest(req, res, '用户ID格式错误');
        }
        
        // 生成缓存键
        const cacheKey = generateCacheKey('permission', 'codes', `user_${userId}`);
        
        // 尝试从缓存获取
        const cachedPermissionCodes = await cacheService.get(cacheKey);
        if (cachedPermissionCodes) {
            logger.debug('从缓存获取用户权限码列表');
            await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'user_codes', operation_desc: 'list', target_entity_type: 'user', target_entity_id: userId });
            return success(req, res, '获取用户权限码成功', cachedPermissionCodes);
        }
        
        const permissionCodes = await PermissionModel.getPermissionCodesByUserId(userId);
        
        // 设置缓存
        await cacheService.set(cacheKey, permissionCodes, 3600);
        
        await logAudit(req, { action_type: 'view', module_code: 'permission', business_type: 'user_codes', operation_desc: 'list', target_entity_type: 'user', target_entity_id: userId });
        return success(req, res, '获取用户权限码成功', permissionCodes);
    } catch (err) {
        logger.error('获取用户权限码失败:', { error: err });
        return serverError(req, res, '获取用户权限码失败');
    }
};

// 更新权限信息
const updatePermission = async (req, res) => {
    try {
        const { id } = req.body;
        const updateData = req.body;

        const currentUserId = req.user?.id;
        // 验证ID是否存在
        if (!id || !validateId(id)) {
            return badRequest(req, res, '权限ID不能为空且格式错误');
        }

        // 验证基础必填字段
        const requiredValidation = validateRequired(req.body, ['permission_name', 'permission_code', 'module_code', 'permission_type', 'operation_type']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        // API权限
        if (updateData.permission_type === '2') {
            // 输入验证
            const requiredValidation = validateRequired(req.body, ['api_path', 'api_method']);
            if (!requiredValidation.isValid) {
                return badRequest(req, res, requiredValidation.message);
            }
        }


        // 执行更新
        const result = await PermissionModel.updatePermission(id, updateData,currentUserId);

        // 清除权限相关缓存
        await clearPermissionRelatedCache(id);
        // 同时调用原有的清除方法以保持兼容性
        // if (PermissionModel.clearPermissionCache) {
        //     await PermissionModel.clearPermissionCache();
        

        await logAudit(req, { action_type: 'update', module_code: 'permission', business_type: 'permission', operation_desc: 'update', target_entity_type: 'permission', target_entity_id: id, after_data: updateData });
        return success(req, res, '权限更新成功', { affectedRows: result });
    } catch (err) {
        logger.error('更新权限失败:', { error: err });
        if (err.message === '权限不存在') {
            return notFound(req, res, '权限不存在');
        }
        return serverError(req, res, '更新权限失败');
    }
};

// 删除权限
const deletePermission = async (req, res) => {
    try {
        const { id } = req.params;
        const currentUserId = req.user?.id;

        if (!validateId(id)) {
            return badRequest(req, res, '权限ID格式错误');
        }

        // 执行软删除
        await PermissionModel.softDeletePermission(id, currentUserId);

        // 清除权限相关缓存
        await clearPermissionRelatedCache(id);
        // 同时调用原有的清除方法以保持兼容性
        // if (PermissionModel.clearPermissionCache) {
        //     await PermissionModel.clearPermissionCache();
        // }

        await logAudit(req, { action_type: 'delete', module_code: 'permission', business_type: 'permission', operation_desc: 'delete', target_entity_type: 'permission', target_entity_id: id });
        return success(req, res, '权限删除成功');
    } catch (err) {
        logger.error('删除权限失败:', { error: err });
        if (err.message === '权限不存在') {
            return notFound(req, res, '权限不存在');
        }
        if (err.message === '权限已删除') {
            return badRequest(req, res, '权限已被删除');
        }
        if (err.message === '系统权限不能删除') {
            return badRequest(req, res, '系统权限不能删除');
        }
        return serverError(req, res, '删除权限失败');
    }
};

// 检查用户权限是否需要更新
const checkPermissionUpdate = async (req, res) => {
    try {
        const userId = req.user?.id;
        
        if (!userId) {
            return badRequest(req, res, '用户ID不能为空');
        }

        // 检查用户的角色是否发生变化
        const hasRoleChanged = await PermissionModel.hasUserRoleChanged(userId);
        
        // 检查用户角色的权限是否发生变化
        const hasPermissionChanged = await PermissionModel.hasRolePermissionChanged(userId);
        
        // 综合判断：角色变化或权限变化都需要更新
        const needUpdate = hasRoleChanged || hasPermissionChanged;
        
        logger.info('权限更新检查', { 
            userId, 
            needUpdate, 
            hasRoleChanged, 
            hasPermissionChanged 
        });
        
        return success(req, res, '检查权限更新状态成功', { 
            needUpdate,
            hasRoleChanged,
            hasPermissionChanged
        });
    } catch (err) {
        logger.error('检查权限更新失败:', { error: err });
        return serverError(req, res, '检查权限更新失败');
    }
};

// 批量删除权限
const batchDeletePermission = async (req, res) => {
    try {
        const { ids } = req.body;
        const currentUserId = req.user?.id;

        // 验证输入
        if (!Array.isArray(ids) || ids.length === 0) {
            return badRequest(req, res, '权限ID列表不能为空');
        }

        for (const id of ids) {
            if (!validateId(id)) {
                return badRequest(req, res, `权限ID格式错误: ${id}`);
            }
        }

        // 限制批量删除数量，防止误操作
        if (ids.length > 100) {
            return badRequest(req, res, '批量删除数量不能超过100个');
        }

        // 执行批量删除
        const result = await PermissionModel.batchSoftDeletePermissions(ids, currentUserId);

        // 清除权限相关缓存
        await clearPermissionRelatedCache();
        // 同时调用原有的清除方法以保持兼容性
        // if (PermissionModel.clearPermissionCache) {
        //     await PermissionModel.clearPermissionCache();
        // }

        return success(req, res, '批量删除权限成功', {
            deletedCount: result.deletedCount,
            deletedIds: result.deletedIds
        });
    } catch (err) {
        logger.error('批量删除权限失败:', { error: err });
        
        // 处理各种错误情况
        if (err.message.includes('权限ID列表不能为空') || 
            err.message.includes('无效的权限ID') ||
            err.message.includes('部分权限不存在') ||
            err.message.includes('系统权限不能删除') ||
            err.message.includes('权限已被删除')) {
            return badRequest(req, res, err.message);
        }
        
        return serverError(req, res, '批量删除权限失败');
    }
};

// 创建新权限
const createPermission = async (req, res) => {
    try {
        const permissionData = req.body;

        const currentUserId = req.user?.id;
        // 验证基础必填字段
        const requiredValidation = validateRequired(req.body, ['permission_name', 'permission_code', 'module_code', 'permission_type', 'operation_type']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        // API权限
        if (permissionData.permission_type === '2') {
            // 输入验证
            const requiredValidation = validateRequired(req.body, ['api_path', 'api_method']);
            if (!requiredValidation.isValid) {
                return badRequest(req, res, requiredValidation.message);
            }
        }

        // 执行创建
        const permissionId = await PermissionModel.createPermission(permissionData,currentUserId);

        // 清除权限相关缓存
        await clearPermissionRelatedCache();
        // 同时调用原有的清除方法以保持兼容性
        // if (PermissionModel.clearPermissionCache) {
        //     await PermissionModel.clearPermissionCache();
        // }

        return success(req, res, '权限创建成功', {
            id: permissionId,
            ...permissionData
        }, 200);
    } catch (err) {
        logger.error('创建权限失败:', { error: err });
        if (err.message === '权限名称、权限编码和模块编码为必填字段') {
            return badRequest(req, res, err.message);
        }
        if (err.message === '权限编码已存在') {
            return badRequest(req, res, err.message);
        }
        return serverError(req, res, '创建权限失败');
    }
};

// 批量恢复权限
const batchRestorePermissions = async (req, res) => {
  try {
    const { ids } = req.body;
    const currentUserId = req.user.id;

    const result = await PermissionModel.batchRestorePermissions(ids, currentUserId);
    
    // 清除权限相关缓存
    await clearPermissionRelatedCache();
    
    success(res, '批量恢复权限成功', result);
  } catch (error) {
    logger.error('批量恢复权限失败', { error: error, userId: req.user?.id });
    error(res, error.message || '批量恢复权限失败');
  }
};

// 硬删除过期权限（管理员维护功能）
const hardDeleteOldPermissions = async (req, res) => {
  try {
    const { daysOld = 180 } = req.body; // 默认180天
    const currentUserId = req.user.id;

    const result = await PermissionModel.hardDeleteOldPermissions(daysOld, currentUserId);
    
    // 清除权限相关缓存
    await clearPermissionRelatedCache();
    // 同时调用原有的清除方法以保持兼容性
    // if (PermissionModel.clearPermissionCache) {
    //     await PermissionModel.clearPermissionCache();
    // }
    
    success(res, '硬删除过期权限成功', result);
  } catch (error) {
    logger.error('硬删除过期权限失败', { error: error, userId: req.user?.id });
    error(res, error.message || '硬删除过期权限失败');
  }
};

// 获取已删除的权限列表
const getDeletedPermissions = async (req, res) => {
  try {
    const { page = 1, limit = 10, moduleCode, search } = req.query;
    
    const filters = {};
    if (moduleCode) filters.moduleCode = moduleCode;
    if (search) filters.search = search;
    
    // 生成缓存键
    const cacheKey = generateCacheKey('permission', 'deleted', `${page}_${limit}_${JSON.stringify(filters)}`);
    
    // 尝试从缓存获取
    const cachedResult = await cacheService.get(cacheKey);
    if (cachedResult) {
        logger.debug('从缓存获取已删除权限列表');
        return success(res, '获取已删除权限列表成功', cachedResult);
    }

    const result = await PermissionModel.getDeletedPermissions(
      parseInt(page), 
      parseInt(limit), 
      filters
    );
    
    // 设置缓存
        await cacheService.set(cacheKey, result, 3600);
    
    success(res, '获取已删除权限列表成功', result);
  } catch (error) {
    logger.error('获取已删除权限列表失败', { error: error, userId: req.user?.id });
    error(res, error.message || '获取已删除权限列表失败');
  }
};

// 恢复单个权限
const restorePermission = async (req, res) => {
  try {
    const { id } = req.params;
    const currentUserId = req.user.id;

    await PermissionModel.restorePermission(id, currentUserId);
    
    // 清除权限相关缓存
    await clearPermissionRelatedCache(id);
    // 同时调用原有的清除方法以保持兼容性
    // if (PermissionModel.clearPermissionCache) {
    //     await PermissionModel.clearPermissionCache();
    // }
    
    success(res, '恢复权限成功');
  } catch (error) {
    logger.error('恢复权限失败', { error: error, userId: req.user?.id, permissionId: req.params.id });
    error(res, error.message || '恢复权限失败');
  }
};

// 清除权限相关缓存的辅助函数
const clearPermissionRelatedCache = async (permissionId = null) => {
    try {
        // 清除权限列表缓存（使用模式匹配）
        await cacheService.clearByPattern(getCacheKeyPattern('permission','list'));
        
        // 如果指定了权限ID，清除该权限的详情缓存
        if (permissionId) {
            const cacheKey = generateCacheKey('permission','item',`permission_${permissionId}`);
            await cacheService.del(cacheKey);
        } else {
            await cacheService.clearByPattern(getCacheKeyPattern('permission','item'));
        }
        
        // 清除所有用户权限码缓存
        await cacheService.clearByPattern(getCacheKeyPattern('permission','codes'));
        
        // 清除所有权限验证缓存
        await cacheService.clearByPattern(getCacheKeyPattern('permission','verify'));
        
        logger.debug('权限相关缓存已清除');
    } catch (error) {
        logger.error('清除权限缓存失败:', { error });
        // 不抛出错误，继续执行后续操作
    }
};

// 验证用户是否拥有指定权限
const verifyUserPermission = async (req, res) => {
    try {
        const userId = req.user?.id || req.params.userId;
        const { permission_code } = req.params;

        if (!userId || !validateId(userId)) {
            return badRequest(req, res, '用户ID格式错误');
        }

        if (!permission_code) {
            return badRequest(req, res, '权限码不能为空');
        }

        // 生成缓存键
        const cacheKey = generateCacheKey('permission', 'verify', `${userId}_${permission_code}`);
        
        // 尝试从缓存获取
        const cachedResult = await cacheService.get(cacheKey);
        if (cachedResult !== null) {
            logger.debug('从缓存获取权限验证结果');
            return success(req, res, '验证用户权限成功', { hasPermission: cachedResult });
        }

        const hasPermission = await PermissionModel.checkUserPermission(userId, permission_code);
        
        // 设置缓存，有效期较短
        await cacheService.set(cacheKey, hasPermission, 300); // 5分钟
        
        return success(req, res, '验证用户权限成功', { hasPermission });
    } catch (err) {
        logger.error('验证用户权限失败:', { error: err });
        return serverError(req, res, '验证用户权限失败');
    }
};

module.exports = {
  getPermissions,
  getPermission,
  getUserPermissionCodes,
  updatePermission,
  deletePermission,
  createPermission,
  batchDeletePermission,
  batchRestorePermissions,
  hardDeleteOldPermissions,
  getDeletedPermissions,
  restorePermission,
  checkPermissionUpdate,
  verifyUserPermission
};